/**
 * 处理token存储和获取的工具函数
 */

// token在localStorage中的key
const TOKEN_KEY = 'wms_token'

/**
 * 设置token
 * @param {string} token - JWT token
 */
export const setToken = (token) => {
  localStorage.setItem(TOKEN_KEY, token)
}

/**
 * 获取token
 * @returns {string|null} 存储的token或null
 */
export const getToken = () => {
  return localStorage.getItem(TOKEN_KEY)
}

/**
 * 移除token
 */
export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY)
}

/**
 * 检查是否有token
 * @returns {boolean} 是否有token
 */
export const hasToken = () => {
  return !!getToken()
}

/**
 * 解析JWT token
 * @param {string} token - JWT token
 * @returns {Object|null} 解析后的payload部分或null
 */
export const parseToken = (token) => {
  try {
    if (!token) return null
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        })
        .join('')
    )
    return JSON.parse(jsonPayload)
  } catch (e) {
    console.error('解析token失败:', e)
    return null
  }
}

export default {
  setToken,
  getToken,
  removeToken,
  hasToken,
  parseToken
} 